package com.ucap.weking.guangan.fragments.fragmentContent;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ucap.weking.guangan.Activitys.LiveOnlineActivity;
import com.ucap.weking.guangan.Activitys.LiveOnlineListContentActivity;
import com.ucap.weking.guangan.R;
import com.ucap.weking.guangan.adapter.LiveOnlineAdapter;
import com.ucap.weking.guangan.base.BaseFragment;
import com.ucap.weking.guangan.bean.ItemListHeadLiveOnlineBean;
import com.ucap.weking.guangan.bean.ItemListOnlineBean;
import com.ucap.weking.guangan.bean.LiveOnlineMinuteBean;
import com.ucap.weking.guangan.dataUri.DataUri;
import com.ucap.weking.guangan.httpTools.HttpCallRequest;
import com.ucap.weking.guangan.test.TestData;
import com.ucap.weking.guangan.views.LoadingListView;
import com.ucap.weking.guangan.views.MyToast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by weking on 2017/11/13.
 * 在线访谈
 */

public class LiveOnlineFragment extends BaseFragment {

    @InjectView(R.id.lv_content)
    LoadingListView lvContent;
    @InjectView(R.id.srlRefresh)
    SwipeRefreshLayout srlRefresh;
    @InjectView(R.id.tv_is_null)
    TextView tvIsNull;
    private LiveOnlineAdapter adapter;
    private int numow = 1;//页面开始角标
    private int num = 10;//页面结束角标
    private ArrayList<ItemListOnlineBean.RowsBean> mData;
    private View liveOnline;
    private ImageView ivLiveImage;
    private TextView tvLiveTitle;
    private TextView tvLiveTitleTitle;
    private TextView tvLiveTimer;
    private TextView tvGuest;
    private LinearLayout llTimer;
    private LinearLayout llGuest;


    @Override
    public void setData() {
        numow = 1;
        num = 10;
        mData = new ArrayList<>();
        adapter = new LiveOnlineAdapter(mData);
        lvContent.setAdapter(adapter);
        getData(mData, numow, num);
        srlRefresh.setColorSchemeResources(R.color.colorPrimary);
        srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                numow = 1;
                num = 10;
                mData.clear();
                getData(mData, numow, num);
            }
        });

        lvContent.setInterface(new LoadingListView.IloadListener() {
            @Override
            public void onLoad() {
                getData(mData, numow += 10, num += 10);
            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("position", "onItemClick: " + position);
                if (position <= 0) {

                } else if (mData.size() > 0 && position > -1 && position <= mData.size()) {
                    ItemListOnlineBean.RowsBean item = adapter.getItem(position - 1);
                    Intent intent = new Intent(getActivity(), LiveOnlineListContentActivity.class);
                    intent.putExtra("title", item.getTITLE());
                    intent.putExtra("id", item.getID());
                    startActivity(intent);

                }
            }
        });

    }

    private void getData(final ArrayList<ItemListOnlineBean.RowsBean> mData, final int startNum, int endNum) {
        Log.i("在线访谈列表", DataUri.getLIVE_ONLINE(startNum, endNum));
        if (startNum == 1)
            srlRefresh.setRefreshing(true);
        HttpCallRequest.callRequest(DataUri.getLIVE_ONLINE(startNum, endNum), new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                Log.i("liveOnlineNumber", "numow:  " + numow + " num: " + num);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        ItemListOnlineBean itemListOnlineBean = gson.fromJson(body, ItemListOnlineBean.class);
                        List<ItemListOnlineBean.RowsBean> rows = itemListOnlineBean.getRows();
                        if (rows != null && rows.size() > 0) {
                            mData.addAll(rows);
                            adapter.notifyDataSetChanged();
                            srlRefresh.setRefreshing(false);
                            lvContent.loadComplete();
                            tvIsNull.setVisibility(View.GONE);
                        } else if (rows == null || rows.size() < 1) {
                            MyToast.showTrue(getContext(), "已加载全部！");
                            srlRefresh.setRefreshing(false);
                            lvContent.loadComplete();
                            tvIsNull.setVisibility(View.GONE);
                            if (numow > 1) {
                                numow -= 10;
                                num -= 10;
                            }
                        }


                    }
                });
            }

            @Override
            public void onErr(Exception e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        srlRefresh.setRefreshing(false);
                        lvContent.loadComplete();
                        adapter.notifyDataSetChanged();
                        if (numow > 1) {
                            numow -= 10;
                            num -= 10;
                        }
                        if (mData.size() < 1) {
                            tvIsNull.setVisibility(View.VISIBLE);
                        } else {
                            tvIsNull.setVisibility(View.GONE);
                            MyToast.showTrue(getContext(), "连接超时，请检查网路连接！");
                        }
                        Log.i("number", "err   numow:  " + numow + " num: " + num);
                    }
                });

            }
        });
        setLiveOnline();
    }

    /**
     * 获取列表头部直播信息
     */
    public void setLiveOnline() {
        lvContent.removeHeaderView(liveOnline);
        HttpCallRequest.callRequest(DataUri.getLIVE_ONLINE(), new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                if (!TextUtils.isEmpty(body)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("在线访谈直播", "onRequest: " + body);
                            try {
                                Gson gson = new Gson();
                                ItemListHeadLiveOnlineBean itemListHeaLiveOnlineBean = gson.fromJson(body, ItemListHeadLiveOnlineBean.class);
                                List<ItemListHeadLiveOnlineBean.Rows1Bean> rows1Beans = itemListHeaLiveOnlineBean.getRows1();
                                if (rows1Beans != null && rows1Beans.size() > 0) {//直播有数据
                                    Glide.with(getActivity())
                                            .load(rows1Beans.get(0).getPIC())
                                            .into(ivLiveImage);
                                    tvLiveTitle.setText(rows1Beans.get(0).getTITLE());
                                    tvLiveTimer.setText(rows1Beans.get(0).getTIME());
                                    tvGuest.setText(rows1Beans.get(0).getGUEST());
                                    lvContent.addHeaderView(liveOnline);
                                    liveOnline.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            getLiveContent();

                                        }
                                    });

                                } else if (rows1Beans == null || rows1Beans.size() < 1) {//未有直播数据，就显示rows3访谈预告数据
                                    List<ItemListHeadLiveOnlineBean.Rows3Bean> rows3Beans = itemListHeaLiveOnlineBean.getRows3();
                                    if (rows3Beans != null && rows3Beans.size() > 0) {
                                        Glide.with(getActivity())
                                                .load(rows3Beans.get(0).getPATHANDURL())
                                                .into(ivLiveImage);
                                        tvLiveTitle.setText(rows3Beans.get(0).getCONTENT());
                                        tvLiveTitleTitle.setVisibility(View.GONE);
                                        llTimer.setVisibility(View.GONE);
                                        llGuest.setVisibility(View.GONE);
                                        liveOnline.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                MyToast.showTrue(getContext(), "直播尚未开始！");
                                            }
                                        });
                                        lvContent.addHeaderView(liveOnline);
                                    }

                                }
                            } catch (Exception e) {

                            }
                        }
                    });
                }
            }

            @Override
            public void onErr(Exception e) {

            }
        });

    }


    /**
     * 获取直播详细
     */
    public void getLiveContent() {
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("请稍后...");
        progressDialog.show();
        HttpCallRequest.callRequest(DataUri.getLIVE_ONLINE_CONTENT(), new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(body)) {
                            try {
                                Gson gson = new Gson();
                                LiveOnlineMinuteBean liveOnlineMinuteBean = gson.fromJson(body, LiveOnlineMinuteBean.class);
                                List<LiveOnlineMinuteBean.RowsBean> rows = liveOnlineMinuteBean.getRows();
                                if (rows != null && rows.size() > 0) {
                                    LiveOnlineMinuteBean.RowsBean rowsBean = rows.get(0);
                                    long startTime = rowsBean.getSTARTTIME().getTime();//开始时间
                                    long endTime = rowsBean.getENDTIME().getTime();//结束时间
                                    long nowTimer = System.currentTimeMillis();
                                    if (nowTimer >= startTime && nowTimer <= endTime) {//大于开始时间，小于结束时间表示当前正在直播
                                        Bundle bundle = new Bundle();
                                        bundle.putString("title", rowsBean.getTITLE());
                                        bundle.putString("timer", rowsBean.getTIME());
                                        bundle.putString("guest", rowsBean.getGUEST());
                                        bundle.putString("explain", rowsBean.getDESCRIBE());
                                        bundle.putString("video", rowsBean.getVIDEO());
                                        Intent intent = new Intent(getActivity(), LiveOnlineActivity.class);
                                        intent.putExtra("live_data", bundle);
                                        getActivity().startActivity(intent);
                                    } else {
                                        MyToast.showTrue(getContext(), "当前尚未直播！");
                                    }
                                }
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                progressDialog.dismiss();
                            }
                        }

                    }
                });
            }

            @Override
            public void onErr(Exception e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        MyToast.showTrue(getContext(), "连接超时，检查网络重试！");
                    }
                });
            }
        });
    }

    @Override
    public void intiView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.frgament_content1_news, null);
        ButterKnife.inject(this, view);
        flContent.addView(view);
        intiHeadLive();
    }

    public void intiHeadLive() {
        liveOnline = LayoutInflater.from(getContext()).inflate(R.layout.item_live_online_head, null);
        //简介图片
        ivLiveImage = (ImageView) liveOnline.findViewById(R.id.iv_image);
        //主题内容
        tvLiveTitle = (TextView) liveOnline.findViewById(R.id.tv_title);
        //主题
        tvLiveTitleTitle = (TextView) liveOnline.findViewById(R.id.tv_title_title);
        //时间
        tvLiveTimer = (TextView) liveOnline.findViewById(R.id.tv_timer);
        //嘉宾
        tvGuest = (TextView) liveOnline.findViewById(R.id.tv_guest);
        //时间布局
        llTimer = (LinearLayout) liveOnline.findViewById(R.id.ll_timer);
        //嘉宾布局
        llGuest = (LinearLayout) liveOnline.findViewById(R.id.ll_guest);
    }
}
